package cn.hinglo.gameclaw.data.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * @createTime: 2018/5/8
 * @author: HingLo
 * @description: Ehcache缓存工具
 */
public class EhcacheUtil {
    /**
     * 使用默认的配置文件创建 cacheManager
     */
    private final static CacheManager MANAGER = CacheManager.create();

    /**
     * 从缓存中取值
     *
     * @param cacheName 缓存的名称
     * @param key       缓存的key
     * @return 返回取出的值
     */
    public static <T> T get(String cacheName, Object key) {
        Cache cache = MANAGER.getCache(cacheName);
        if (cache != null) {
            Element element = cache.get(key);
            if (element != null) {
                return (T) element.getObjectValue();
            }
        }
        return null;
    }

    /**
     * 添加数据到缓存
     *
     * @param cacheName 缓存的名称
     * @param key       key
     * @param value     值
     */
    public static void put(String cacheName, Object key, Object value) {
        Cache cache = MANAGER.getCache(cacheName);
        if (cache != null) {
            cache.put(new Element(key, value));
        }
    }

    /**
     * 删除缓存信息
     *
     * @param cacheName 缓存名称
     * @param key       key
     * @return 是否删除成功
     */
    public static boolean remove(String cacheName, Object key) {
        Cache cache = MANAGER.getCache(cacheName);
        if (cache != null) {
            return cache.remove(key);
        }
        return false;
    }


}
